package com.lyncs.ods.modules.setting.service.impl;

import com.lyncs.ods.common.exception.ApiException;
import com.lyncs.ods.common.web.RequestHolder;
import com.lyncs.ods.constant.LanguageEnum;
import com.lyncs.ods.modules.setting.model.CmsText;
import com.lyncs.ods.modules.setting.mapper.CmsTextMapper;
import com.lyncs.ods.modules.setting.service.CmsTextService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author alex
 * @since 2022-07-03
 */
@Service
public class CmsTextServiceImpl extends ServiceImpl<CmsTextMapper, CmsText> implements CmsTextService {

    PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("{", "}");

    @Override
    public String getContent(Long id, Map<String, String> paramMap) {
        return propertyPlaceholderHelper.replacePlaceholders(getLanguageText(id, RequestHolder.language()), paramMap::get);
    }

    private String getLanguageText(Long id, String language) {
        CmsText cmsText = this.getById(id);
        Assert.notNull(cmsText, "failed to get language text");
        if (StringUtils.isEmpty(language) || LanguageEnum.ZH_CN.getLanguage().equals(language)) {
            return cmsText.getZhCn();
        } else if (LanguageEnum.ZH_HK.getLanguage().equals(language)) {
            return cmsText.getZhHk();
        } else if (LanguageEnum.EN_US.getLanguage().equals(language)) {
            return cmsText.getEnUs();
        } else {
            throw new ApiException("failed to get language text");
        }
    }
}
